package bean;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import DAO.AvaliacaoAntropometricaDAO;
import DAO.HemodialiseDAO;
import DAO.PacienteDAO;
import Utils.Uteis;

public class RelatorioAvaliacaoBean {
	private Date dataInicial;
	private Date dataFinal;
	
	public Date getDataInicial() {
		return dataInicial;
	}
	
	public void setDataInicial(Date dataInicial) {
		this.dataInicial = dataInicial;
	}
	
	public Date getDataFinal() {
		return dataFinal;
	}
	
	public void setDataFinal(Date dataFinal) {
		this.dataFinal = dataFinal;
	}
	
	public void gerarRelatorio()
	{
		try {			
			String file = FacesContext.getCurrentInstance().getExternalContext().getRealPath("jasper/rel_avaantropometrica.jasper");			
			java.sql.Date data_inicio = Uteis.javaDate2SqlDate(this.dataInicial);
			java.sql.Date data_fim = Uteis.javaDate2SqlDate(this.dataFinal);			
			ResultSet res = AvaliacaoAntropometricaDAO.relatorioAvaliacaoAntropometrica(data_inicio, data_fim);		 
			JRResultSetDataSource jrrs = new JRResultSetDataSource(res);
			Map<String, Object> parameters = new HashMap<String, Object>();			
			byte[] bytes = null;
			ServletOutputStream outpustream = null;
			
			JasperPrint print = JasperFillManager.fillReport(file, parameters, jrrs);			
			bytes = JasperExportManager.exportReportToPdf(print);
			
			FacesContext context = FacesContext.getCurrentInstance();  
			HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();			
			response.setContentType("application/pdf");  
			response.setHeader("Content-Disposition","attachment; filename=\"relatorioAvaliacao.pdf\"");  
			outpustream = response.getOutputStream();
			outpustream.write(bytes, 0, bytes.length);
			
			outpustream.flush();  
			outpustream.close();			
			
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (JRException e) {
			e.printStackTrace();
		} catch(java.text.ParseException e) {
			e.printStackTrace();
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
}
